package cn.edu.gduf.luowowo.website.web.interceptor;

import cn.edu.gduf.luowowo.cache.service.IUserInfoRedisService;
import cn.edu.gduf.luowowo.member.domain.UserInfo;
import cn.edu.gduf.luowowo.website.annotation.RequiredLogin;
import cn.edu.gduf.luowowo.website.util.CookieUtil;
import com.alibaba.dubbo.config.annotation.Reference;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 登录检查拦截器
 */
public class LoginInterceptor implements HandlerInterceptor {

    @Reference
    private IUserInfoRedisService userInfoRedisService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //判断用户是否登录
        String token = CookieUtil.getToken(request);
        if (token != null) {
            UserInfo user = userInfoRedisService.getUserByToken(token);
            //将用户信息放到session中
            request.getSession().setAttribute("userInfo", user);
            //登录放行
            if (user != null) {
                //说明用户已登录，延长在redis中的缓存时间
                userInfoRedisService.expireToken(token);
                //重置cookie的失效时间
                CookieUtil.addCookie(response, token);
                return true;
            }
        }
        //判断访问的是动态资源还是静态资源
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }
        //判断当前访问的方法有无贴RequiredLogin注解
        HandlerMethod handlerMethod = (HandlerMethod) handler;
        RequiredLogin requiredLoginAnno = handlerMethod.getMethodAnnotation(RequiredLogin.class);
        if (requiredLoginAnno == null) {
            return true;
        }
        //未登录去到登录页面
        response.sendRedirect("/login.html");
        return false;
    }
}
